package com.sentinel.utils;

import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@RefreshScope
public class AuthFilter implements GlobalFilter, Ordered {


    /**
     * 不需要认证的url配置类
     */

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE - 1;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getPath();

        // 1. 跳过不需要认证的url
//        if (shouldSkip(url)) {
//            return chain.filter(exchange);
//        }

        ServerWebExchange mutatedExchange = checkToken(exchange);
        return chain.filter(mutatedExchange);
    }

    private ServerWebExchange checkToken(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();


        // 设置header
        ServerHttpRequest mutatedRequest = request.mutate()
                .header("enterpriseId", "1111")

                .build();


        return exchange.mutate().request(mutatedRequest).build();
    }

    /**
     * 检查url是否需要授权
     *
     * @param url 当前请求路径
     * @return true: 不需要授权，false: 需要授权
     * @author xiaoweiqian
     * @date 2021/09/05
     */
    private boolean shouldSkip(String url) {
        // 路径匹配器，比如/oauth/** 可以匹配 /oauth/token、/oauth/check_token等
        PathMatcher pathMatcher = new AntPathMatcher();
//        for (String path : noAuthUrlConfig.getNoAuthUrls()) {
//            if (pathMatcher.match(path, url)) {
//                return true;
//            }
//        }
        return false;
    }


}
